import { appCacheDir, BaseDirectory } from "@tauri-apps/api/path";
import { create } from "@tauri-apps/plugin-fs";
import { invoke } from "@tauri-apps/api/core";
import { upload } from "../api/upload";
import { useSelector } from "react-redux";
import { useEffect } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import { HoverBorderGradient } from "./ui/hover-border-gradient";
import { listen } from "@tauri-apps/api/event";
import { toast, Toaster } from "sonner";
export default function Upload() {
  const user = useSelector((state) => state.user.username);
  const getByteArray = (file) => {
    return new Promise((resolve, reject) => {
      let fileReader = new FileReader();
      fileReader.readAsArrayBuffer(file);
      fileReader.onload = function (ev) {
        const array = new Uint8Array(ev.target.result);
        const fileByteArray = [];
        for (let i = 0; i < array.length; i++) {
          fileByteArray.push(array[i]);
        }
        resolve(array); // successful
      };
      fileReader.onerror = reject; // call reject if error
    });
  };
  /**
   *
   * @deprecated
   */
  const upload_handler = async (event) => {
    console.log(user);
    const file = event.target.files[0];
    console.log(file);
    //TODO: 换成react-notify
    if (file.type !== "text/csv") {
      return;
    }
    let byte_array = await getByteArray(file);
    console.log(file.type);
    let cache_path = await appCacheDir();
    console.log(cache_path);
    //保存到本地
    const local_file = await create(`${file.name}`, {
      baseDir: BaseDirectory.AppCache,
    });
    await local_file.write(byte_array);
    await local_file.close();
    let token = await invoke("upload_token");
    console.log(file.name);

    console.log(token);
    upload({
      token,
      file,
      key: `${user}/${file.type === "text/csv" ? "csv" : file.type}/${
        file.name
      }`,
    })
      .then(() => {})
      .catch(() => {});
    //从本地上传至七牛云
  };
  let upload_promise;
  const async_upload_handler = async () => {
    const file = await open({
      multiple: false,
      directory: false,
    });
    upload_promise = new Promise((resolve, reject) => {
      listen("upload", (event) => {
        if (event.payload.Ok == undefined) {
          reject(event.payload.Err);
        }
        resolve(event.payload.Ok);
      });
    });
    await invoke("async_upload", { username: "root", path: file });
    toast.promise(upload_promise, {
      loading: "上传中...",
      success: (data) => {
        return data;
      },
      error: (message) => {
        return message;
      },
    });
  };
  useEffect(() => {});
  return (
    <>
      <HoverBorderGradient
        as="button"
        containerClassName="rounded-full"
        className="dark:bg-black bg-white text-black dark:text-white flex items-center space-x-2"
        onClick={async_upload_handler}
      >
        <p>上传文件</p>
      </HoverBorderGradient>
      <Toaster></Toaster>
    </>
  );
}
